import { makeAutoObservable } from 'mobx'

class DictsStore {
  dicts: Record<string, { key: string; value: number }[]> = {}
  // 初始化Promise，用于等待初始化完成
  initPromise: Promise<void> | null = null

  constructor() {
    makeAutoObservable(this)
    this.initDictsStore()
  }

  // 初始化用户信息，返回Promise以便等待完成
  initDictsStore(): Promise<void> {
    // 如果已经有初始化Promise，直接返回
    if (this.initPromise) {
      return this.initPromise
    }

    // 创建并存储初始化Promise
    this.initPromise = this.fetchDictsFromServer()
    return this.initPromise
  }

  setDicts(dicts: Record<string, { key: string; value: number }[]>) {
    this.dicts = dicts
  }
  getDict(dictName: string) {
    return this.dicts[dictName]
  }

  getDictValue(dictName: string, key: string) {
    const dict = this.dicts[dictName]
    if (dict) {
      const item = dict.find((item) => item.key === key)
      if (item) {
        return item.value
      }
    }
    return null
  }

  getDictKey(dictName: string, value: number) {
    const dict = this.dicts[dictName]
    if (dict) {
      const item = dict.find((item) => item.value === value)
      if (item) {
        return item.key
      }
    }
    return null
  }

  getDictColor(dictName: string, value: number) {
    if (dictName !== 'serviceStatus') return ''
    const dict = this.dicts['serviceStatus']
    if (dict) {
      const item = dict.find((item) => item.value === value)
      if (item) {
        if (item.value === 0) {
          // 勘探后条件不允许
          return '#f5222d'
        } else if (item.value === 1) {
          // 待审核
          return '#faad14'
        } else if (item.value === 2) {
          // 审核通过
          return '#52c41a'
        } else if (item.value === 3) {
          // 审核驳回
          return '#f5222d'
        } else if (item.value === 4) {
          // 勘探中
          return '#1890ff'
        } else if (item.value === 5) {
          // 勘探完成，安装中
          return '#1890ff'
        } else if (item.value === 6) {
          // 安装完成，工单完结
          return '#52c41a'
        }
        return ''
      }
    }
    return ''
  }

  async fetchDictsFromServer(): Promise<void> {
    // 确保Apis已经初始化
    await import('../uitls/apiUtils').then(({ waitForApisInitialized }) => {
      return waitForApisInitialized()
    })
    // 发起请求获取字典数据
    const dictsAndNames = [
      {
        dictName: 'serviceStatus',
        dictApi: Apis.cm.BusinessStatus(),
      },
      {
        dictName: 'serviceType',
        dictApi: Apis.cm.BusinessType(),
      },
    ]

    try {
      // 多个字典同时调用，完成后再设置
      const dicts = await Promise.allSettled(
        dictsAndNames.map((i) => i.dictApi)
      ).then((results) => {
        const dicts: Record<string, { key: string; value: number }[]> = {}
        results.forEach((result, index) => {
          if (result.status === 'fulfilled') {
            const dict = result.value
            const dictName = dictsAndNames[index].dictName
            dicts[dictName] = dict
          }
        })
        return dicts
      })
      // 设置字典数据
      this.setDicts(dicts)
    } catch (error) {
      // 处理错误
      console.error('Failed to fetch dicts from server:', error)
    } finally {
      // 初始化完成后，将Promise置为null
      // this.initPromise = null
    }
  }
}

export default new DictsStore()
